package com.gzz.orchid.common.core.tuple;

import com.gzz.orchid.common.core.exception.ValidationException;
import lombok.Value;

import java.util.Arrays;
import java.util.Objects;

/**
 * 电话号码
 *
 * @author higmd
 */
@Value
public class PhoneNumber {
    String value;
    // 构造函数
    public PhoneNumber(String value) {
        if (Objects.isNull(value)) {
            throw new ValidationException("Number不能为空");
        } else if (isValid(value)) {
            throw new ValidationException("Number格式错误");
        }
        this.value = value;
    }

    /**
     * 判断区号
     */
    private static boolean isAreaCode(String prefix) {
        String[] areas = new String[]{"0571", "021", "010"};
        return Arrays.asList(areas).contains(prefix);
    }

    /**
     * 验证号码格式
     */
    public static boolean isValid(String number) {
        String pattern = "^0?[1-9]{2,3}-?\\d{8}$";
        return number.matches(pattern);
    }

    /**
     * 获取区号
     */
    public String getAreaCode() {
        for (int i = 0; i < value.length(); i++) {
            String prefix = value.substring(0, i);
            if (isAreaCode(prefix)) {
                return prefix;
            }
        }
        return null;
    }
}
